﻿using DICOM_PROJECT.DAL.Security;
using DICOM_PROJECT.Extension;
using DICOM_PROJECT.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace DICOM_PROJECT.Controllers
{
    [CustomAuthorize(Roles = "Admin")]
    public class AdminController : BaseController
    {
        //
        // GET: /Admin/
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public string GetPatientInfo(SearchModel search)
        {
            if (!ModelState.IsValid)
            {
                return "invalid_id";
            }
            var user = new UserProfile();
            if (search.type == 1)//search with patientID
            {
                user = db.UserProfiles.FirstOrDefault(m => m.UserProfileID == search.id);
            }
            else
            {
                user = db.UserProfiles.FirstOrDefault(m => m.SocialID == search.id.ToString() || m.SocialID == "0" + search.id.ToString());
            }
            if (user == null)
            {
                return "no_matched_data";
            }
            var userResult = new UserProfileModel { ID = user.UserProfileID, SocialID = user.SocialID, Name = user.Name, Birthday = user.Birthday.ToString("dd/MM/yyyy"), Male = user.Male, Address = user.Address, Phone = user.Phone };

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(userResult);
        }
        
        [HttpPost]
        public string ResetPassword(int userID)
        {
            var user = db.UserProfiles.FirstOrDefault(m => m.UserProfileID == userID);
            string[] b = user.Birthday.ToString("dd/MM/yyyy").Split(new char[] { '/' });
            user.Password = String.Concat(b);
            db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            return "reset_pass_success";
        }
        
        [HttpPost]
        public string GetUserType()
        {
            var userTypes = db.Roles.Select(u => u.RoleName).ToList();
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(userTypes);
        }

        [HttpPost]
        public string CreateUser(UserProfileCreateModel user)
        {
            if (user.SocialID != null)
            {
                var existUser = db.UserProfiles.FirstOrDefault(m => m.SocialID == user.SocialID || m.SocialID == "0" + user.SocialID || "0" + m.SocialID == user.SocialID);
                if (existUser != null)
                {
                    return "exist_socialid";
                }
            }
            UserProfile newUser;
            switch (user.UserType)
            {
                case "Doctor":
                    newUser = new Doctor();
                    break;
                case "Radiologist":
                    newUser = new Radiologist();
                    break;
                case "Admin":
                    newUser = new Admin();
                    break;
                case "Assistant":
                    newUser = new Assistant();
                    break;
                default:
                    newUser = new Patient();
                    break;
            }
            newUser.SocialID = user.SocialID;
            newUser.Name = user.Name;

            string[] b = user.Birthday.Split(new char[] {'/'});
            newUser.Birthday = new DateTime(int.Parse(b[2]), int.Parse(b[1]), int.Parse(b[0]));

            newUser.Password = String.Concat(newUser.Birthday.ToString("dd/MM/yyyy").Split(new char[] {'/'}));

            newUser.Male = user.Male;
            newUser.Address = user.Address;
            newUser.Phone = user.Phone;

            newUser.UserType = user.UserType;
            List<Role> roles = new List<Role>();
            roles = db.Roles.Where(r => r.RoleName == "Patient" || r.RoleName == user.UserType).ToList();
            newUser.Roles = roles;
            db.UserProfiles.Add(newUser);
            db.SaveChanges();
            var result = new UserProfileModel
            {
                ID = newUser.UserProfileID,
                SocialID = newUser.SocialID,
                Name = newUser.Name,
                Birthday = newUser.Birthday.ToString("dd/MM/yyyy"),
                Male = newUser.Male,
                Address = newUser.Address,
                Phone = newUser.Phone
            };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(result);
        }

        [HttpPost]
        public string GetUser(int id)
        {
            var user = db.UserProfiles.FirstOrDefault(u => u.UserProfileID == id);
            var userResult = new UserProfileUpdateModel{
                ID = user.UserProfileID.ToString(),
                SocialID = user.SocialID,
                Name = user.Name,
                Birthday = user.Birthday.ToString("dd/MM/yyyy"),
                Male = user.Male,
                Address = user.Address,
                Phone = user.Phone,
                UserType = user.UserType
            };
            var userTypes = db.Roles.Select(u => u.RoleName).ToList();
            ArrayList result = new ArrayList();
            result.Add(userResult);
            result.Add(userTypes);
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(result);
        }

        [HttpPost]
        public string UpdateUser(UserProfileUpdateModel user)
        {
            var uUser = db.UserProfiles.FirstOrDefault(u => u.UserProfileID.ToString() == user.ID);
            if (user.SocialID != null)
            {
                var existUser = db.UserProfiles.FirstOrDefault(m => m.SocialID == user.SocialID || m.SocialID == "0" + user.SocialID || "0" + m.SocialID == user.SocialID);
                if (existUser != null && existUser.UserProfileID !=uUser.UserProfileID)
                {
                    return "exist_socialid";
                }
            }
            uUser.SocialID = user.SocialID;
            uUser.Name = user.Name;

            string[] b = user.Birthday.Split(new char[] { '/' });
            uUser.Birthday = new DateTime(int.Parse(b[2]), int.Parse(b[1]), int.Parse(b[0]));

            uUser.Male = user.Male;
            uUser.Address = user.Address;
            uUser.Phone = user.Phone;
            if (uUser.UserType != user.UserType)
            {
                //switch (user.UserType)
                //{
                //    case "Doctor":
                //        uUser = (Doctor)uUser;
                //        break;
                //    case "Radiologist":
                //        uUser = (Radiologist)uUser;
                //        break;
                //    case "Admin":
                //        uUser = (Admin)uUser;
                //        break;
                //    case "Assistant":
                //        uUser = (Assistant)uUser;
                //        break;
                //    default:
                //        uUser = (Patient)uUser;
                //        break;
                //}
                uUser.Roles.Clear();
                List<Role> roles = new List<Role>();
                roles = db.Roles.Where(r => r.RoleName == "Patient" || r.RoleName == user.UserType).ToList();
                uUser.Roles = roles;
            }
            uUser.UserType = user.UserType;
            db.Entry(uUser).State = EntityState.Modified;
            db.SaveChanges();
            try
            {
                var updateSQL = @"UPDATE UserProfile SET Discriminator=@p0 WHERE UserProfileID=@p1";
                var rowCount = db.Database.ExecuteSqlCommand(updateSQL, user.UserType, uUser.UserProfileID);
            }
            catch (DataException /* dex */)
            {
            }
            var result = new UserProfileModel
            {
                ID = uUser.UserProfileID,
                SocialID = uUser.SocialID,
                Name = uUser.Name,
                Birthday = uUser.Birthday.ToString("dd/MM/yyyy"),
                Male = uUser.Male,
                Address = uUser.Address,
                Phone = uUser.Phone
            };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(result);
        }
	}
}